package cn.xuyun.cc.tcp.coder;

import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.nio.charset.Charset;
import java.util.Date;

import org.apache.log4j.Logger;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.handler.codec.frame.DelimiterBasedFrameDecoder;
import org.jboss.netty.handler.codec.frame.Delimiters;
import org.jboss.netty.handler.codec.frame.FrameDecoder;
import org.jboss.netty.handler.codec.string.StringDecoder;
import org.jboss.netty.handler.codec.string.StringEncoder;

import cn.xuyun.cc.tcp.TcpServerHandler;

import com.sun.org.apache.xerces.internal.impl.dv.util.HexBin;

public class Decoder extends FrameDecoder{

	private static Logger logger=Logger.getLogger(Decoder.class);
	
	
	

	@Override
	public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
		logger.info("port 4000,client connected!");
		ChannelPipeline p = ctx.getPipeline();
		p.addLast("handler", new TcpServerHandler());
	}
	
	
	
	@Override
	protected Object decode(ChannelHandlerContext context, Channel channel, ChannelBuffer buffer) throws Exception {

		buffer.markReaderIndex();
		
		byte first = buffer.readByte();
		if (first !='$') {
			
			throw new IllegalArgumentException("not begin with $");
		}
		
		int bg = buffer.readerIndex();
		
		byte cur=0 ;
		
		String reqstr=null;
		String rescode=null;
		String data=null;
		
		while(buffer.readable())
		{
			cur = buffer.readByte();
			if(cur=='&')
			{
				//$101&0&2|id|pwd#
			//bg-> ^   ^ -> buffer.readerIndex()
				int length=buffer.readerIndex()-bg-1;
				String curstr=buffer.toString(bg,length,Charset.forName("UTF-8"));
				bg=buffer.readerIndex();
				if(reqstr==null)
				{
					reqstr=curstr;
				}else if(rescode==null)
				{
					rescode=curstr;
				}else{
					throw new IllegalArgumentException("to many &");
				}
			}
			else if(cur=='#'){
				int length = buffer.readerIndex() - bg -1;
				data=buffer.toString(bg,length,Charset.forName("UTF-8"));
				logger.info(reqstr+","+rescode+","+data);
				return new String[]{reqstr,rescode,data};
			}
		}
		
		
		buffer.resetReaderIndex();
		return null;
	}
	
	public static void main(String[] args) throws Exception{
		byte s='$';
		System.out.printf("%x\n", s);
		System.out.println(HexBin.encode("$".getBytes("UTF8")));
	}
}
